package com.noassertions.data;

import java.util.ArrayList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;

import com.noassertions.domain.Rider;

public class DAOImpl extends HibernateDaoSupport implements DAOInterface 
{

    protected final Log log = LogFactory.getLog(getClass());

    @Transactional
    public void insertRider(Rider rider)
    {
    	getHibernateTemplate().saveOrUpdate(rider);
    	
    }

    @Transactional(readOnly = true)
	public Rider getRiderByID(int id)
	{
		Rider rider = (Rider) getHibernateTemplate().get(Rider.class, id);
		return rider;
	}
    
    /**
     * Find the total number of riders in the system
     * This is typically used as an ceiling when grabbing a rider by a random number
     * 
     * @return count of riders in system
     */
    @Transactional
    public Long getRiderCount() {
    	String query = "select count(*) from Rider";
    	//TODO: Update so that iterator isn't created to get count
    	return (((Long) getHibernateTemplate().find(query).iterator().next()).longValue());
    }
    
    /**
     * 
     * Find the count of fits a rider has in the fit table
     * 
     * @param riderId the id of the rider we're looking for
     * @return count of fits for a given rider
     */
    @Transactional
    public Long getFitCount(int riderId) {
    	String query = "from Fit where riderid = ?";
    	//TODO: Update so that iterator isn't created to get count

    	return (((Long) getHibernateTemplate().find(query).iterator().next()).longValue());
    }

    @Transactional(readOnly = true)
	public ArrayList getRiderByRiderId(int riderId) {
    	//TODO: we're only ever going to get one rider, do we need a list?
    	String query = "from Rider where riderid = ?";
		ArrayList riderList = (ArrayList)getHibernateTemplate().find(query, riderId);
		return riderList;
	}
    
    @Transactional(readOnly = true)
	public ArrayList getFitsByRiderId(int riderId) {
    	String query = "from Fit where riderid = ?";
		ArrayList fitList = (ArrayList)getHibernateTemplate().find(query, riderId);
		return fitList;
	}

    @Transactional(readOnly = true)
	public ArrayList getImagesByFitId(int fitId) {
    	String query = "from Image where fitid = ?";
		ArrayList imageList = (ArrayList)getHibernateTemplate().find(query, fitId);
		return imageList;
	}
}